package com.zy.controller;

import com.zy.constant.MessageConstant;
import com.zy.entity.Result;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

	@RequestMapping("/getUsername")
	public Result getUsername(){
		try {
			//Spring Security在认证成功后，会将用户信息保存到框架提供的上下文对象中
			//底层的实现原理是session会话
			//(返回的这个User对象就是我们自定义SpringSecurityUserService类中方法的返回值)
			Authentication user = SecurityContextHolder.getContext().getAuthentication();
			return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getName());
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(false, MessageConstant.GET_USERNAME_FAIL);
		}

	}
}
